from sklearn.datasets import load_breast_cancer
import pandas as pd
from sklearn.model_selection import train_test_split
import xgboost as xgb
from sklearn.metrics import roc_auc_score
import shap

# 加载数据
data = load_breast_cancer()
X = pd.DataFrame(data.data, columns=data.feature_names)
y = data.target

# 查看数据集的相关信息
print("数据集特征形状：", data.data.shape)
print("目标变量形状：", data.target.shape)
print("数据集特征名称：", data.feature_names)
print("目标变量名称：", data.target_names)

# 划分数据集（70%训练集，30%测试集）
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建XGBoost模型
model = xgb.XGBClassifier(eval_metric='mlogloss')
# 训练模型
model.fit(X_train, y_train)
# 预测
y_pred = model.predict(X_test)
# 模型评估
roc_auc = roc_auc_score(y_test, model.predict_proba(X_test)[:, 1])
print(f"AUC: {roc_auc:.4f}")

# SHAP部分
# 创建SHAP解释器
explainer = shap.TreeExplainer(model)
# 计算SHAP值
shap_values = explainer.shap_values(X_train)
# 绘制SHAP特征重要性图
shap.summary_plot(shap_values, X_train, plot_type="bar")
shap.summary_plot(shap_values, X_train)
shap.plots.force(explainer.expected_value, shap_values[125])